package cn.school.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("/showCookieVisit")
public class ShowCookieVisitServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        //先找到cookie,然后给他+1，再塞回去
        resp.setContentType("text/html;charset=utf-8");
        Cookie cr[]=request.getCookies();
        //假定，那个cookie的名字叫 visitNums
        Cookie c=null;
        for(int i=0;cr!=null&&i<cr.length;i++){
            if(cr[i].getName().equals("visitNums")){
                c=cr[i];
                break;
            }
        }
        if(c==null){
            c=new Cookie("visitNums","1");
        }else{
            c.setValue(String.valueOf(Integer.parseInt(c.getValue())+1));
        }
        //再发给浏览器
        c.setMaxAge(3600*24*7);
        resp.addCookie(c);
        resp.getWriter().println("这是您第"+c.getValue()+"访问本地址！");
    }
}
